package com.excel.write.base;

import com.excel.entity.CCell;
import com.excel.write.CRow;
import com.excel.write.ExcelContent;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.List;

public abstract class BaseExcelWrite implements ExcelXlsWrite {
    private Workbook workbook;

    public BaseExcelWrite(String fileName) {
        if (fileName.endsWith(".xls")) {
            workbook = new HSSFWorkbook();
        } else {
            workbook = new XSSFWorkbook();
        }
    }

    @Override
    public final void write(List<ExcelContent> excelContents) {
        if (workbook != null) {
            try {
                for (ExcelContent excelContent : excelContents) {
                    Sheet xssfSheet = workbook.createSheet(excelContent.getName());
                    Row row;

                    List<CCell> headers = excelContent.getHeaders();
                    int rowId = 0;
                    row = xssfSheet.createRow(rowId++);
                    for (int i = 0; i < headers.size(); i++) {
                        CCell cCell = headers.get(i);
                        Cell cell = row.createCell(i, cCell.getCellType());
                        setCell(cCell, cell);
                    }
                    if (headers.isEmpty()) {
                        rowId--;
                    }
                    List<CRow> rows = excelContent.getcRow();
                    for (CRow cRow : rows) {
                        row = xssfSheet.createRow(rowId++);
                        List<CCell> names = cRow.getCells();
                        for (int i = 0; i < names.size(); i++) {
                            CCell cCell = names.get(i);
                            Cell cell = row.createCell(i, cCell.getCellType());
                            setCell(cCell, cell);
                        }
                    }
                }
                write(workbook);
                workbook.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setCell(CCell cCell, Cell cell) {
        String value = cCell.getValue();
        switch (cCell.getCellType()) {
            case NUMERIC:
                cell.setCellValue(Double.parseDouble(value));
                break;
            case FORMULA:
                cell.setCellFormula(value);
                break;
            default:
                cell.setCellValue(value);
        }
    }

    protected abstract void write(Workbook workbook);
}
